import { WebDriver } from "selenium-webdriver";
import * as fs from 'fs';
import * as path from 'path';
import sharp from 'sharp';
import { screenshotFolderPath } from '../../lib/utility.js';
import { performSmoothScroll } from "./scroll.js";
import { AndroidConfig } from "../../profile/android/android_config.js";

/**
 * 从内容描述中提取点赞数（支持"万"为单位）
 * @param {Array} contentDescs 内容描述数组
 * @returns {number} 点赞数
 */
export function extractLikeCount(contentDescs: string[]): number {
    let likeCount = 0;
    const likeEntry = contentDescs.find(desc => desc.includes('点赞'));
    if (likeEntry) {
      const match = likeEntry.match(/点赞\s*([^\s]+)\s*万?/);
      if (match && match[1]) {
        likeCount = parseFloat(match[1]);
        if (likeEntry.includes('万')) {
          likeCount *= 10000;
        }
      }
    }
    return likeCount;
  }
  
  /**
   * 从内容描述中提取收藏数（支持"万"为单位）
   * @param {Array} contentDescs 内容描述数组
   * @returns {number} 收藏数
   */
  export function extractCollectCount(contentDescs: string[]): number {
    let collectCount = 0;
    const collectEntry = contentDescs.find(desc => desc.includes('收藏') && !desc.includes('获赞'));
    if (collectEntry) {
      const match = collectEntry.match(/收藏\s*([^\s]+)\s*万?/);
      if (match && match[1]) {
        collectCount = parseFloat(match[1]);
        if (collectEntry.includes('万')) {
          collectCount *= 10000;
        }
      }
    }
    return collectCount;
  }
  
  /**
   * 从内容描述中提取评论数（支持"万"为单位）
   * @param {Array} contentDescs 内容描述数组
   * @returns {number} 评论数
   */
  export function extractCommentCount(contentDescs: string[]): number {
    let commentCount = 0;
    const commentEntry = contentDescs.find(desc => desc.includes('评论') && !desc.includes('评论框'));
    if (commentEntry) {
      const match = commentEntry.match(/评论\s*([^\s]+)\s*万?/);
      if (match && match[1]) {
        commentCount = parseFloat(match[1]);
        if (commentEntry.includes('万')) {
          commentCount *= 10000;
        }
      }
    }
    return commentCount;
  }
  
  /**
 * 从内容描述中提取图片数量
 * @param {Array} contentDescs 内容描述数组
 * @returns {number} 图片数量
 */
export function extractImageCount(contentDescs: string[]): number {
    let imageCount = 0;
    const imageEntry = contentDescs.find(desc => desc.includes('共') && desc.includes('张'));
    if (imageEntry) {
      const match = imageEntry.match(/共\s*([^\s]+)\s*张/);
      if (match && match[1]) {
        imageCount = parseInt(match[1], 10);
      }
    }
    return imageCount;
  }

/**
 * 从内容描述中提取标题
 * @param {Array} contentDescs 内容描述数组
 * @returns {string} 标题
 */
export function extractTitle(contentDescs: string[]): string {
  // 规则1：优先提取首条非噪音短文本（长度<30且不含日期/互动关键词）
  const titleCandidate = contentDescs.find(desc => 
      desc.length > 5 && desc.length < 30 &&
      !/^\d{2}-\d{2}\s|\d+天前|点赞|收藏|评论|分享|共\s*\d+\s*张/.test(desc)
  );
  
  // 规则2：若首条无效，则提取包含品牌关键词的短文本（如"爱他美"）
  if (!titleCandidate) {
      const brandTitle = contentDescs.find(desc => 
          desc.length < 50 && /爱他美|奶粉|宝宝/i.test(desc)
      );
      return brandTitle || '';
  }
  
  return titleCandidate;
}

/**
* 从内容描述中提取文本内容
* @param {Array} contentDescs 内容描述数组
* @returns {string} 文本内容
*/
export function extractContent(contentDescs: string[]): string {
  // 规则1：提取最长且含品牌关键词的文本（排除噪音）
  const content = contentDescs.reduce((longest, desc) => {
      const isContent = desc.length > 20 && 
          !/^\d{2}-\d{2}\s|共\s*\d+\s*条评论|点赞|收藏|评论|分享|关注/.test(desc) &&
          /爱他美|奶粉|配方|营养/i.test(desc);
      return isContent && desc.length > longest.length ? desc : longest;
  }, '');
  
  // 规则2：若未找到，则返回第一条长文本
  return content || contentDescs.find(desc => desc.length > 50) || '';
}

/**
 * 从内容描述中提取发布时间并转换为YYYY/MM/DD格式
 * @param {WebDriver} driver WebDriver 实例
 * @param {string[]} contentDescs 内容描述数组
 * @returns {Promise<string>} 发布时间（格式：YYYY/MM/DD）
 */
export async function extractPublishDate(
  driver: WebDriver,
  contentDescs: string[]
): Promise<string> {
  const maxRetries = 10;
  let retryCount = 0;

  while (retryCount < maxRetries) {
    const now = new Date();

    for (const desc of contentDescs) {
      // 1. “今天”
      if (desc.includes('今天')) {
        return toYYYYMMDD(now);
      }
      // 2. “昨天”
      if (desc.includes('昨天')) {
        const d = new Date(now);
        d.setDate(d.getDate() - 1);
        return toYYYYMMDD(d);
      }
      // 3. 完整日期 YYYY/M/D 或 YYYY-MM-DD
      const fullMatch = desc.match(/(\d{4})[/-](\d{1,2})[/-](\d{1,2})/);
      if (fullMatch) {
        const [, y, m, d] = fullMatch;
        return `${y}/${pad(m)}/${pad(d)}`;
      }
      // 4. 原有的 MM-DD
      const shortMatch = desc.match(/(\d{2})-(\d{2})(?!\d)/);
      if (shortMatch) {
        const [, m, d] = shortMatch;
        return `${now.getFullYear()}/${m}/${d}`;
      }
    }

    // 如果一轮里没找到，再尝试滚动加载新内容
    try {
      await driver.sleep(3000);
      await performSmoothScroll(driver, AndroidConfig.device.deviceName, 3, 'standard');
      const pageSource = await driver.getPageSource();
      const textMatches = pageSource.match(/text="([^"]*[\u4e00-\u9fa5\d/-]+[^"]*)"/g);
      if (!textMatches) break;
      contentDescs = textMatches.map(m => m.replace(/text="([^"]+)"/, '$1'));
    } catch {
      break;
    }

    retryCount++;
  }

  return '';
}

function toYYYYMMDD(d: Date): string {
  return `${d.getFullYear()}/${pad(d.getMonth() + 1)}/${pad(d.getDate())}`;
}
function pad(v: number | string): string {
  return v.toString().padStart(2, '0');
}

  
  /**
   * 截取并保存首图
   * @param driver WebDriver 实例
   * @param noteId 笔记ID，用于命名截图文件
   * @returns 返回保存图片的路径
   */
  export async function captureFirstImage(driver: WebDriver, noteId: string): Promise<string> {
    try {
      // 确保截图目录存在
      if (!fs.existsSync(screenshotFolderPath)) {
        fs.mkdirSync(screenshotFolderPath, { recursive: true });
      }
  
      // 截取整个屏幕
      const screenshot = await driver.takeScreenshot();
      const imageBuffer = Buffer.from(screenshot, 'base64');
  
      // Get image metadata to know its dimensions
      const metadata = await sharp(imageBuffer).metadata();
      const imageWidth = metadata.width || 0;
      const imageHeight = metadata.height || 0;
  
      console.log(`Screenshot dimensions: ${imageWidth}x${imageHeight}`);
  
      // 定义裁剪区域（需要根据实际情况调整）
      const desiredCropArea = {
        left: 0,
        top: 200,
        width: 720,
        height: 800
      };
  
      // Adjust crop area to fit within image boundaries
      const cropArea = {
        left: Math.max(0, desiredCropArea.left),
        top: Math.max(0, desiredCropArea.top),
        width: Math.min(desiredCropArea.width, imageWidth - Math.max(0, desiredCropArea.left)),
        height: Math.min(desiredCropArea.height, imageHeight - Math.max(0, desiredCropArea.top))
      };
  
      // Check if the resulting crop area is valid
      if (cropArea.width <= 0 || cropArea.height <= 0) {
          throw new Error(`Invalid crop area. Screenshot: ${imageWidth}x${imageHeight}, Desired: ${JSON.stringify(desiredCropArea)}`);
      }
  
      // 构建保存路径
      const imagePath = path.join(screenshotFolderPath, `${noteId}.png`);
  
      // 使用sharp进行裁剪并保存
      await sharp(imageBuffer)
        .extract(cropArea)
        .toFile(imagePath);
  
      console.log(`首图已保存到: ${imagePath}`);
      return imagePath;
    } catch (error) {
      console.error('截取首图失败:', error);
      throw error;
    }
  }